﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ServiceModel.Activation;
using System.ServiceModel;
using System.IO;
using System.ServiceModel.Web;
using System.Net;
using System.Security;
using System.Collections.Specialized;

namespace COFE.Web.Services
{
    /// <summary>
    /// Services that enables looking up an entry by using file paths.
    /// </summary>
    [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
    [ServiceBehavior(InstanceContextMode = InstanceContextMode.PerCall)]
    public class LookupServices : ILookupServices
    {

        public LookupServices()
        {
            
        }

        public void Lookup(string path, string rel, string trail, string json)
        {

            ServicesUtils.Execute<string>(
           (p) =>
           {
               string desturi;
               path = ServicesUtils.UrlPathToCOFEPath(path);
               Entry foundEntry = ServiceConstants.Profile.LookupEntry(path);
               if (foundEntry == null) throw new FileNotFoundException();
                
               if (rel != null)
               {
                   var foundLink = (foundEntry.GetLinks().FirstOrDefault((link) =>
                    { return link.RelationString.Equals(rel, StringComparison.InvariantCultureIgnoreCase); }));
                   if (foundLink == null) throw new NotSupportedException();

                   desturi = foundLink.Uri;
               }
               else
               {
                   desturi = ServiceConstants.Templates.FormatTemplate(ServiceConstants.Templates.Entry,
                       new Dictionary<string, string>() { { "#id#", foundEntry.ID.ToString() } });

                   if (trail != null)
                       desturi += "/" + trail;

               }

               ServicesUtils.SetRedirect(desturi, true, "rel", "trail");
               
           }, path);
        }
    }
}